package tutorial.api.new_api.xls;


import com.example.SpecialApplicationAfter4Example;
import com.example.SpecialApplicationBefore4Example;
import com.wholefarm.model.SpecailApplicationInterface;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableWorkbook;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import public_util.dao.PublicExportFile2ServerMapper;
import public_util.database.ConnectionFactory;
import public_util.model.*;
import public_util.pack_4_stable.tools.CodeGenerateUtil;
import public_util.pack_4_stable.tools.DateTool;
import public_util.pack_4_stable.tools.OSSTool;
import public_util.pack_4_stable.tools.StringTool;
import public_util.servlet.ServletParent;
import public_util.servlet.db_tool.Data2ParserXls;
import public_util.tool_4_handle.Tool_4_Servlet;
import system_api_4_trade.DuzikaiSpecialApplicationFactory;
import system_api_4_trade.SpecialApplicationAfter;
import system_api_4_trade.SpecialApplicationBefore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工具类放这里方便复制
 */
class Tutorial4XlsTool {



    private static Logger logger = Logger.getLogger(Tutorial4XlsTool.class);


    public static ReturnData show_xls_export(SqlSessionFactory sqlSession, ServletParent thisParent, HttpServletResponse response, HttpServletRequest request, Map<String, String[]> new_map)
    {
        HttpSession hsession = request.getSession();
        ReturnData resultData = new ReturnData();


        SqlSession session = sqlSession.openSession();
        try {
            List<PublicMiddleTable> content = new ArrayList<PublicMiddleTable>();

            PublicMiddleTable middleTable = new PublicMiddleTable();
            middleTable.setMid_table_remark_001("--a--");
            middleTable.setMid_table_remark_001("--b--");
            middleTable.setMid_table_remark_001("--c--");

            content.add(middleTable);
            content.add(middleTable);
            content.add(middleTable);

            String show_title_xls = "xls的名称";//名称
            //项目ID mid_table_remark_040，项目部委mid_table_remark_006、项目名称mid_table_remark_001、【公司编号选中】、申报好处mid_table_remark_008、历史立项数量mid_table_remark_010、申报时间mid_table_remark_009、申报要求mid_table_remark_011
            String excelRowTitle = "序号-_-项目ID-_-项目部委-_-项目名称";
            String excelBody[] = new String[content.size()];
            String now_str = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");


            for (int i = 0; i < content.size(); i++)
            {
                PublicMiddleTable contentItem = content.get(i);
                String selectValue = contentItem.getMid_table_remark_012();
                excelBody[i] = (i+1)  +"-_-" + contentItem.getMid_table_remark_001() + "-_-"
                        + contentItem.getMid_table_remark_002() + "-_-" + contentItem.getMid_table_remark_003()
                        + "";
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            WritableWorkbook book = Workbook.createWorkbook(baos);
            /*
             * 创建excel文件
             */
            String excelSheetName = "查询比对内容" + show_title_xls;
            String sheet_title = excelSheetName;
            XlsSheetData sheetData =  new XlsSheetData(excelSheetName, sheet_title, excelRowTitle, excelBody);
            List<XlsSheetData> listSheet = new ArrayList<XlsSheetData>();
            listSheet.add(sheetData);
            String current_data = DateTool.getCurrentDateStr(DateTool.C_DATA_PATTON_YYYYMMDDHHMMSS);
            String file_name = excelSheetName + "_" + current_data + ".xls";
            /*
             * 将excel文件上传到服务器中
             */
            String filePath = OSSTool.upload_sheets_as_xls_file(listSheet, file_name, 0, null);
            System.out.println(filePath);
            /*
             * 上传成功
             */
            if (filePath != null) {
                /*
                 * excel导入导出
                 */
                PublicExportFile2ServerMapper fileMapper = session.getMapper(PublicExportFile2ServerMapper.class);
                HashMap<String, Object> para = new HashMap<String, Object>();
                para.put(Const4PublicDataBase.PARA_id_public_data_admin_user, 800);
                para.put(Const4PublicDataBase.PARA_url_4_file, filePath);
                para.put(Const4PublicDataBase.PARA_file_remark, "导出项目比对表");
                para.put(Const4PublicDataBase.PARA_is_online, 0);
                para.put(Const4PublicDataBase.PARA_type_app_export, 1011);
                para.put(Const4PublicDataBase.PARA_type_inner_app_export, 101);
                fileMapper.insertFile2Server(para);
                session.commit();
                HashMap<String, Object> returnMap = new HashMap<String, Object>();
                returnMap.put(Const4PublicDataBase.PARA_page_content, filePath);
                resultData.setStatus(0);
                resultData.setReturnData(returnMap);
            }

        }catch(Exception e)
        {
            resultData.setMsg(e.toString());
            return resultData;
        }
        resultData.setStatus(0);
        return resultData;
    }



    /**
     * 从API调用时, 我们采用这个入口
     * @param sqlSession
     * @param thisParent
     * @param response
     * @param request
     * @return
     */
    public static ReturnData api_process_entrance(SqlSessionFactory sqlSession, ServletParent thisParent, HttpServletResponse response, HttpServletRequest request)
    {
        HttpSession hsession = request.getSession();
        ReturnData resultData = new ReturnData();
        String id_public_export_file_2_server = request.getParameter(Const4PublicDataBase.PARA_id_public_export_file_2_server);
//        resultData = Tool_4_Servlet.checkAccessType(hsession, resultData, 102);
//        if (resultData.getStatus() != 0) {
//            return resultData;
//        }
        logger.info("---id_public_export_file_2_server--" + id_public_export_file_2_server);

        if (!Tool_4_Servlet.checkParaNotShow(id_public_export_file_2_server)) {
            resultData.setMsg(ReturnData.DEFAULT_MSG_4_PARA_WRONG);
            return resultData;
        }

        SqlSession session = sqlSession.openSession();

        try {

            ParSerXlsData resultPara = ParSerXlsData.checkHeader4ImportFiles(session, id_public_export_file_2_server);
            Data2ParserXls parser_result = resultPara.getXlsContent();
            String errMsg = parser_result.err_string;
            if (!"".equals(errMsg))
            {
                resultData.setMsg(errMsg);
                return resultData;
            }

            int module_id = parser_result.type_inner_app_export;
            logger.info("module_id:" + module_id);

            Sheet currentSeet = parser_result.currentSeet;
            String result = common_import_queue(resultPara.getUrl(), session, currentSeet, resultData);
            if (!"".equals(result))
            {
                resultData.setMsg(result);
                return resultData;
            }
        }catch(Exception e)
        {
            resultData.setMsg(e.toString());
            return resultData;
        }
        resultData.setStatus(0);
        return resultData;
    }


    /**
     * main函数的入口在这里
     * @param from_filePath
     * @param session
     * @param sheetIdx
     */
    protected  static void main_process_entrance(String from_filePath, SqlSession session, int sheetIdx)
    {
        try {

            File file = new File(from_filePath);
            if (!file.exists())
            {
                logger.info("not exist");
                return;
            }
            System.out.println(file.getAbsolutePath());
            // 这里读出来的workbook作为模版
            Workbook workbook = Workbook.getWorkbook(file);
            int size = workbook.getNumberOfSheets();
            Sheet sheet = workbook.getSheet(sheetIdx);


            ParSerXlsData resultPara = ParSerXlsData.checkHeader4ImportFiles(session, sheet);
            Data2ParserXls parser_result = resultPara.getXlsContent();
            String errMsg = parser_result.err_string;
            if (!"".equals(errMsg))
            {
                logger.error(errMsg);
                return;
            }

            int module_id = parser_result.type_inner_app_export;
            logger.info("module_id:" + module_id);


            String msg = common_import_queue(from_filePath, session, sheet, null);
            logger.info("msg:" + msg);

        }catch(Exception e)
        {
            Tool_4_Servlet.showStackTrace(e);
        }
    }



    private static String common_import_queue(String execlUrl, SqlSession session, Sheet currentSeet, ReturnData resultData) throws Exception
    {
        logger.info("当前xls名称:" + currentSeet.getName());
        int rows = currentSeet.getRows();

        String msg_error_key = CodeGenerateUtil.generateCardNumber() + CodeGenerateUtil.genRadomStr(6);


        for (int i = 2; i < rows; i++)
        {
            String cell_value_000 = null;
            String cell_value_001 = null;
            String cell_value_002 = null;
            String cell_value_003 = null;
            String cell_value_004 = null;
            String cell_value_005 = null;
            String cell_value_006 = null;
            String org_data = null;

            try
            {
                cell_value_000 = currentSeet.getCell(0,i).getContents().trim();//mid_table_remark_006
                cell_value_001 = currentSeet.getCell(1,i).getContents().trim();//mid_table_remark_001
                cell_value_002 = currentSeet.getCell(2,i).getContents().trim();//mid_table_remark_040
                cell_value_003 = currentSeet.getCell(3,i).getContents().trim();//mid_table_remark_010
                cell_value_004 = currentSeet.getCell(4,i).getContents().trim();//mid_table_remark_008
                cell_value_005 = currentSeet.getCell(5,i).getContents().trim();//mid_table_remark_009
                cell_value_006 = currentSeet.getCell(6,i).getContents().trim();//mid_table_remark_011
            }
            catch(Exception e)
            {
                logger.info(e.toString() + "");
                continue;
            }
            logger.info("--cell_value_000---" + cell_value_000);
            logger.info("--cell_value_001---" + cell_value_001);
            logger.info("--cell_value_002---" + cell_value_002);
            logger.info("--cell_value_003---" + cell_value_003);
            logger.info("--cell_value_004---" + cell_value_004);
            logger.info("--cell_value_005---" + cell_value_005);
            logger.info("--cell_value_006---" + cell_value_006);
        }
        return "";
    }


    public static void main(String[] args) throws Exception {


        SpecialApplicationBefore beforeApp = new SpecialApplicationBefore4Example();

        //本地环境
        beforeApp.setConfiguartion_environment(new String[]{SpecailApplicationInterface.LOAD_CONF_TYPE_FROM_DB, "1021"});
        /*按照独自开重构思路, 进行相关的特殊处理的方法*/
        SpecialApplicationAfter afterApp = new SpecialApplicationAfter4Example();
        DuzikaiSpecialApplicationFactory.setInitApplication(beforeApp, afterApp);
        SqlSessionFactory sqlSession = ConnectionFactory.getSession();
        SqlSession session = sqlSession.openSession();
        try
        {

//            String from_filePath = "//Users//fanchen//IdeaProjects//duzikai_-back_-end_-core_4_-example_-version_101//src//main//java//com//example//xls//import_example.xls";
            String from_filePath = "C:\\Users\\Administrator\\IdeaProjects\\shequlinju_back_end_20220913\\src\\main\\java\\tutorial\\api\\new_api\\xls\\会员模板清单_2022_1009.xls";
            logger.info(from_filePath);
            main_process_entrance(from_filePath, session, 0);
        }
        catch(Exception e)
        {
            Tool_4_Servlet.showStackTrace(e);
            logger.info(e);
        }
        finally
        {
            session.close();
        }
    }






}